iT邦幫忙

2024 iThome 鐵人賽

DAY 10
1
DevOps

全端監控技術筆記---從Sentry到Opentelemetry系列 第 10

Day10--後端服務與Sentry---以NodeJS為例

  • 分享至 

  • xImage
  •  

前言

雖然近期討論Sentry幾乎都是在前端的錯誤監控,但別忘了當初Sentry在最一開始的開發目的,是為了處理Django後端的日誌問題和錯誤報警。接下來,我們就來看一下Sentry和後端服務的接合是如何,不過筆者比較熟悉NodeJS,所以大部分的demo會以NodeJS為主

初始化項目

NodeJS express

簡單基於express來寫一個後端server:

  • index.js
const express = require('express');
const cors = require('cors');

const { SENTRY_DSN, PORT } = require('./config');

const app = express();

app.use(cors());
app.get('/', (req, res) => {
    res.send('hello nodejs with sentry');
});
app.listen(PORT, () => {
    console.log(`NodeJS server in: http://localhost:${PORT}`);
});

在Nodejs中初始化Sentry

  • 根據官方文件指示,安裝必要依賴(之前的版本還需要手動按裝@sentry/tracing,但在 7.47.0版本之後就不需要了)
pnpm add @sentry/node @sentry/profiling-node
  • 在Sentry平台上,再另外新增一個project,獲取其DSN url
  • 在Nodejs專案中的根文件最上層,引入Sentry sdk並且初始化:
const Sentry = require('@sentry/node');
const { nodeProfilingIntegration } = require('@sentry/profiling-node');

const { SENTRY_DSN, PORT } = require('./config');

// Ensure to call this before requiring any other modules!
Sentry.init({
    dsn: SENTRY_DSN,
    integrations: [
        // Add our Profiling integration
        nodeProfilingIntegration(),
    ],

    // Add Tracing by setting tracesSampleRate
    // We recommend adjusting this value in production
    tracesSampleRate: 1.0,

    // Set sampling rate for profiling
    // This is relative to tracesSampleRate
    profilesSampleRate: 1.0,
});
  • 在 express 所有controller之後,呼叫Sentry錯誤處理的中間件:
...

app.get('/', (req, res) => {
    res.send('hello nodejs with sentry');
});
app.get('/demo-01', (req, res) => {
    res.json({ message: 'demo api successfully' });
});
// The error handler must be registered before any other error middleware and after all controllers
Sentry.setupExpressErrorHandler(app);

這樣一來,Sentry SDK就可以捕捉在這個express應用中的錯誤,上報到Sentry 平台。

完成設定後,簡單demo看看、查看Sentry平台

拋一個錯誤

  • api:
app.get('/demo-error', (req, res) => {
    throw new Error("Demo Error")
});
  • Sentry display:

image

寫一個長時間的handler

  • api--
app.get('/demo-long', async (req, res) => {
    await sleep(3000);
    res.json({ message: 'demo api successfully' });
});
  • Sentry display:

image

簡單寫一個多段的span

  • api--
app.get('/demo-mulit-with-span', async (req, res) => {
    try {
        const dbResult = await Sentry.startSpan(
            {
                name: 'Mock DB Action',
            },
            async () => {
                // mock db
                await sleep(3000);
                return 'finsh db';
            },
        );
        const otherResult = await Sentry.startSpan(
            {
                name: 'Mock Other Service Action',
            },
            async () => {
                // mock db
                await sleep(2000);
                return 'finsh other service';
            },
        );

        res.json({ message: 'finish multi-action ' });
    } catch (err) {
        Sentry.captureException(err);
        res.status(500).send('Error Happened');
    }
});
  • Sentry display:

image

小結

今天我們簡單在NodeJS中結合Sentry,並且mock一些場景來看Sentry會如何展示。接下來我們將深入理解Sentry是如何對NodeJS應用進行監控的。

ref

ChangeLog

  • 20240924--新增demo圖片、小結
  • 20240920--初稿

上一篇
Day09--Sentry是如何獲取效能指標(下)---web vitals
下一篇
Day11---Sentry在NodeJS中的錯誤監控
系列文
全端監控技術筆記---從Sentry到Opentelemetry13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言